<?php

class Phonebook_model extends CI_Model
{
	private $table = 'phonebook';
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function insert($data)
	{
		$this->db->insert($this->table, $data);
		
		return TRUE;
	}
	
	public function update($data, $id)
	{
		$this->db->where('id', $id);
		$this->db->update($this->table, $data);
		
		return TRUE;
	}
	
	function delete($id)
	{
		$this->db->delete($this->table, array('id' => $id));
		
		return TRUE;
	}
	
	public function addPhoto($data)
	{
		$this->db->insert('phonebook_photo', $data);
		
		return TRUE;
	}
	
	function deletePhoto($id)
	{
		$this->db->delete('phonebook_photo', array('id' => $id)); // delete all photos of someone
		
		return TRUE;
	}
	
	public function getAll($limit, $offset = 0, $search = '')
	{
		$query = $this->db->select()->from($this->table)->limit($limit, $offset)->order_by('name', 'ASC');
		if ($search != '') {
			$query->like('name', $search);
			$query->or_like('mobile1', $search);
			$query->or_like('mobile2', $search);
			$query->or_like('address', $search);
			$query->or_like('email', $search);
			$query->or_like('desc', $search);
		}
		
		return $query->get()->result_array();
	}
	
	public function getTotalRows($search = '')
	{
		if ($search != '') {
			$this->db->like('name', $search);
			$this->db->or_like('mobile1', $search);
			$this->db->or_like('mobile2', $search);
			$this->db->or_like('address', $search);
			$this->db->or_like('email', $search);
			$this->db->or_like('desc', $search);
			return $this->db->count_all_results($this->table);
		} else {		
			return $this->db->count_all($this->table);
		}
	}
	
	public function getDataById($id)
	{
		$query = $this->db->query("SELECT * FROM " . $this->table . " WHERE `id` = {$id}");
		
		return $query->row_array();
	}
	
	public function getPhotos($id)
	{
		$this->db->where('phonebook_id', $id);
		$this->db->order_by('id', 'DESC');
		$query = $this->db->get('phonebook_photo');
		$results = $query->result_array();
		
		return $results;
		
	}
	
	public function getImage($id)
	{
		$this->db->where('id', $id);
		$query = $this->db->get('phonebook_photo');
		$result = $query->row_array();
		
		return $result;
		
	}
	
	public function getTotalPhotos($id)
	{
		$this->db->where('phonebook_id', $id);
		$this->db->from('phonebook_photo');
		$result = $this->db->count_all_results();
		
		return $result;
	}
	
	function deleteSelectedPhoto($pid)
	{
		$this->db->delete('phonebook_photo', array('id' => $pid)); // delete one photo of someone
		
		return TRUE;
	}
}